import PropTypes from 'react-router/lib/PropTypes';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import forEach from 'lodash/forEach'
import times from 'lodash/times'
import Immutable from 'immutable'
const get = Immutable.get;

import * as TotalBudgetAction from '../actions/totalBudget';

import { WeaErrorPage, WeaTools } from 'ecCom';
import { WeaSearchGroup,WeaTop,WeaTab,WeaRightMenu } from 'ecCom';
import {Row,Col,Input,Tabs,Button,Alert,Spin,Icon,Form,Modal} from 'antd';
const createForm = Form.create;
const FormItem = Form.Item;
const confirm = Modal.confirm;
import {WeaTable} from 'comsRedux'
import MyModal from './MyModal'
import ShareModal from './ShareModal'

const WeaTableAction = WeaTable.action;


class TotalBudget extends React.Component {
	static contextTypes = {
		router: PropTypes.routerShape
	}
	constructor(props) {
		super(props);
		//使用redux则不用state
		this.state={
		}
	}
	componentDidMount() {
		//一些初始化请求
		const { actions } = this.props;
		actions.totalBudgetInfo();//高级搜索展示列
		actions.totalBudgetReport({});//查询报表
		actions.setShowSearchAd(true);//高级搜索是否显示
	}
	componentWillReceiveProps(nextProps) {
		const keyOld = this.props.location.key;
		const keyNew = nextProps.location.key;
		//点击菜单路由刷新组件
		if(keyOld !== keyNew) {

		}
		//设置页标题
		//		if(window.location.pathname.indexOf('/') >= 0 && nextProps.title && document.title !== nextProps.title)
		//			document.title = nextProps.title;
	}
	shouldComponentUpdate(nextProps, nextState) {
		//组件渲染控制
		//return this.props.title !== nextProps.title
		return true;
	}
	componentWillUnmount() {
		//组件卸载时一般清理一些状态

	}
	getFields(){
		let fieldsData = this.props.page.info;
		let items = [];
        forEach(fieldsData, (field) => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                    	{WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey, this.props,field)}

                    	
                    </FormItem>),
                colSpan:1
            })
        })
        return items;
	}

	showConfirm() {
		let that  = this;
		const { actions } = this.props;
		confirm({
			className:'fnaConfirm',
		    title: '信息确认',
		    content: '确定要生成报表么?',
		    onOk() {
		    	// console.log(1);
		      // actions.totalBudgetReport({qryFunctionType:1,_guid1:'GUID_620A829B_807B_DC24_9A93_AC431271DAD1'});
		      that.doSearch();
		      actions.setShowSearchAd(false);
		      actions.setShowButtons(true);//weatab右侧按钮显隐
		      that.showSave();
		    },
		    onCancel() {
		    	// console.log('取消');
		    },
		});
	}
	showSave() {
		let that  = this;
		const { actions } = this.props;
		confirm({
			className:'fnaConfirm',
		    title: '信息确认',
		    content: '是否保存查询结果？',
		    onOk() {
		    	actions.setModalVisible(true);
		    },
		    onCancel() {
		    	// console.log('取消');
		    },
		});
	}

	//切换顶部tab
	changeTab(e){
		const { actions } = this.props;
		this.props.actions.changeTab(e);

		if(e==2){
			actions.setShowSearchAd(false);//高级搜索是否显示
			actions.queryData({rptTypeName:'fanRptTotalBudget'});
		}else{
			actions.setShowSearchAd(true);//高级搜索是否显示
			actions.setShowButtons(false);//weatab右侧按钮显隐
			actions.totalBudgetReport({});
		}
	}
	getSearchs() {
        return [
            (<WeaSearchGroup showGroup={true} needTigger={true} title="常用条件" items={this.getFields()} />),
        ]
    }
    doSearch(){
    	const {actions} = this.props;
    	// console.log(this.props.page.orderFields);
    	const value = this.props.page.orderFields;
    	let values = Object.assign({},value,{
    		qryFunctionType:1,
    		_guid1:'GUID_620A829B_807B_DC24_9A93_AC431271DAD1',
    	});//目前该接口不支持动态搜索
    	actions.totalBudgetReport(values);
    }
    getTabButtonsAd() {
    	const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{this.showConfirm();}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    getRightMenu(){
    	let btns = [];
    	btns.push({
    		key: 2,
    		icon: <i className='icon-Right-menu-Custom'/>,
    		content:'显示定制列'
    	});
    	return btns;
    }

    onRightMenuClick(key){
    	const {actions} = this.props;
    	const {sessionkey} = this.props.page;
    	//key=2为显示列定制
    	if(key == '2'){
    		actions.setColSetVisible(sessionkey,true);
    		actions.tableColSet(sessionkey,true)
    	}
    }
    testShare(bool){
    	// console.log(bool);
    	const {actions} = this.props;
    	actions.setShareModal(bool);
    }
	
	render() {
		const { loading, title,tabkey,showSearchAd,showModal,showShareModal,showButtons,actions,sessionkey,sessionkeymodal } = this.props.page;
		// console.log(this.props.page);
		// const columns = this.getColumns();
		// console.log(showShareModal);
		const MyModalTitle = "将当前查询结果保存为";
		const ShareModalTitle = "共享设置";
		const MyModalPersonTitle = "基本信息";
		const ShareModalPersonTitle = `${title}--共享设置`;
		const  footer=[
            <Button key="back" type="ghost" size="large" onClick={()=>this.props.actions.setModalVisible(false)}>返 回</Button>,
            <Button key="submit" type="primary" size="large" loading={this.state.loading} onClick={()=>this.props.actions.setModalVisible(false)}>
              提 交
            </Button>]
        const ShareModalfooter=[
        	<Button key="back" type="ghost" size="large" onClick={()=>this.props.actions.setShareModal(false)}>关 闭</Button>
        ]
		const items =[{a:'报表名称',b:'0570'},{a:'描述',b:'268888882'}]
		const tabDatas=[
			{title:'查询报表',key:"1"},
           	{title:'历史查询结果',key:"2"}
        ];
        const btns = [
            (<Button type="primary" style={{display:showButtons?'inline-block':'none'}} >图表视图</Button>),
            (<Button type="glost" style={{display:showButtons?'inline-block':'none',borderLeft:'1px solid #d9d9d9 !important'}}>保存查询结果</Button>),
            (<Button type="glost" style={{display:showButtons?'inline-block':'none',borderLeft:'1px solid #d9d9d9 !important'}}>导出Excel</Button>),
        ];
        const btnst = [
            (<Button type="primary" disable={false} onClick={()=>{this.props.actions.setShareModal(true);this.props.actions.queryShareModalData({rptTypeName:'fanRptTotalBudget',fnaTmpTbLogId:'2'})}}>批量删除</Button>),
        ];
		return (
			<div>
				<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)} >
            	<WeaTop 
            	loading={loading} 
            	icon={<i className='icon-portal-workflow' />} 
            	iconBgcolor='#55D2D4' 
            	title={title}  
            	buttons={tabkey==1?btns:btnst}
	            showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                onDropMenuClick={this.onRightMenuClick.bind(this)}
            	/>
            	<WeaTab
            		setShowSearchAd={bool=>{this.props.actions.setShowSearchAd(bool)}}
            		hideSearchAd={()=> this.props.actions.setShowSearchAd(false)}
            		buttonsAd={this.getTabButtonsAd()}
            		showSearchAd={showSearchAd}
		            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
		            selectedKey={tabkey}
		            datas={tabDatas}
                    searchType={tabkey==2?['base','advanced']:['base','advanced']}
		            keyParam='key'
		            onChange={this.changeTab.bind(this)}
		        />
		        <WeaTable 
                    hasOrder={true}
                    needScroll={true}
                    sessionkey={sessionkey}
                />
                 <MyModal
                 	title={MyModalTitle}
                 	persontitle={MyModalPersonTitle}
                 	needTigger={true}
                 	showDrop={true}
                 	showModal={showModal}
                 	footer={footer}
                 	iconBgcolor='#55D2D4'
                 	icon={<i className='icon-portal-workflow' />}
                 	items={items}
                 />
                 <ShareModal
                 	title={ShareModalTitle}
                 	persontitle={ShareModalPersonTitle}
                 	showDrop={true}
                 	showModal={showShareModal}
                 	footer={ShareModalfooter}
                 	iconBgcolor='#55D2D4'
                 	icon={<i className='icon-portal-workflow' />}
                 	items={items}
                 	sessionkey={sessionkeymodal}
                 />
                </WeaRightMenu>
            	
            </div>
		)
	}

}
//form 表单与 redux 双向绑定
TotalBudget = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.page.orderFields,...fields});
        // console.log(props);
        // console.log(fields.page);
    },
	mapPropsToFields(props) {
		// console.log(props.page.orderFields);
		return props.page.orderFields;
		// return {}
  	}
})(TotalBudget);





//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}

TotalBudget = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(TotalBudget);

//form 表单与 redux 双向绑定
//TotalBudget = createForm({
//	onFieldsChange(props, fields) {
//		props.actions.saveFields({ ...props.fields, ...fields });
//	},
//	mapPropsToFields(props) {
//		return props.fields;
//	}
//})(TotalBudget);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
	// const { loading, title } = state.fnaTotalBudget;
	// return { loading, title }
	 return {
	 	comsWeaTable,
	  	page: state.fnaTotalBudget,
  };
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
	return {
		actions: bindActionCreators({...TotalBudgetAction,...WeaTableAction}, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(TotalBudget);